// pages/takephoto/takephoto.js
var util = require('../../utils/util.js');
var Constant = require('../../utils/constant.js');
const app = getApp();
var isTaking = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    photo: '/images/img_photo_face.png',
    select: false,
    userName: '',
    cardNumber: '',
    phoneNum: '',
    persondoorno: '',
    hourseNum: '',
    unitno: '',
    typecode: '',
    picBase64: '',
    sex: 0,
    cardType: '',
    wordType: '',
    role: '',
    location: '',
    buildNum: '',
    community: '',
    date: '',
    isVisitor: false,
    faceDetectResult: '',
    deviceId: 'front',
    upload_enable: '',
    x: 0,
    y: 0,
    z: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.takePicType != null){
      if (options.takePicType == 'visitor'){
        console.log("是访客")
        this.setData({
          isVisitor: true,
        })
      }else{
        this.setData({
          userName: options.personname,
          cardNumber: options.personidcardno,
          phoneNum: options.personphoneno,
          hourseNum: options.persondoorno,
          unitno: options.unitno,
          typecode: options.persontype,
          sex: options.sex,
          cardType: options.cardType,
          wordType: options.wordType,
          role: options.role,
          location: options.location,
          community: options.community,
          buildNum: options.buildNum,
          isVisitor:false,
        })
      }
    }

    var DATE = util.formatDate(new Date());
    this.setData({
      date: DATE,
    });
    console.log(this.data.date)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight,
        })
      },
    })

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.startAccelerometer({
      success: function (res) {
        console.log("开始监听")
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
    var offset = 0.2;
    wx.onAccelerometerChange(
      function (res) {
        console.log(res.y)
        that.setData({
          x: res.x,
          y: res.y,
          z: res.z,
        })
        if (!isTaking) {
          if (that.data.z < -offset || that.data.z > offset) {
            that.setData({
              faceDetectResult: '手机上下角度过大，请摆正',
            })
          } else if (that.data.x < -offset || that.data.x > offset) {
            that.setData({
              faceDetectResult: '手机左右角度过大，请摆正',
            })
          } else {
            that.setData({
              faceDetectResult: '',
            })
          }
        }

      })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    wx.stopAccelerometer({
      success: function (res) {
        console.log("停止监听成功")
        that.setData({
          faceDetectResult: '',
        })
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  takePhoto: function(){
    //模拟拍照
    // this.setData({
    //   photo: '/images/test.png',
    //   select: true,
    // })
    // picToBase64(this.data.photo, this);
     
    var that = this;
    wx.stopAccelerometer({
      success: function (res) {
        console.log("停止监听成功")
        that.setData({
          faceDetectResult: '',
        })
      }
    })
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          photo: res.tempImagePath,
          select: true,
        })
        picToBase64(res.tempImagePath, this);
      }
    })

  },
  changeCamera: function(e){
    //back
    var dev = this.data.deviceId;
    var that = this;
    if (dev == "front"){
      dev = "back";
      wx.stopAccelerometer({
        success: function (res) {
          console.log("停止监听成功")
          that.setData({
            faceDetectResult: '',
          })
        }
      })
    }else{
      dev = "front";

      wx.startAccelerometer({
        success: function (res) {
          console.log("开始监听")
        },
        fail: function (res) {
          console.log(res.errMsg)
        }
      })

      var offset = 0.2;
      wx.onAccelerometerChange(
        function (res) {
          console.log(res.y)
          that.setData({
            x: res.x,
            y: res.y,
            z: res.z,
          })
          if (!isTaking) {
            if (that.data.z < -offset || that.data.z > offset) {
              that.setData({
                faceDetectResult: '手机上下角度过大，请摆正',
              })
            } else if (that.data.x < -offset || that.data.x > offset) {
              that.setData({
                faceDetectResult: '手机左右角度过大，请摆正',
              })
            } else {
              that.setData({
                faceDetectResult: '',
              })
            }
          }

        })

    }
    this.setData({
      deviceId: dev
    })
  },

  reTakePhoto: function(e){
    var that = this;
    // let manager = wx.getFileSystemManager();
    // manager.readFile({
    //   filePath: that.data.photo,
    //   encoding: 'base64',
    //   success: function(res){
    //     console.log(res)
    //   },
    //   fail: function (res){
    //     console.log(res)
    //   }
    // })
    wx.startAccelerometer({
      success: function (res) {
        console.log("开始监听")
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
    that.setData({
      photo: '/images/img_photo_face.png',
      faceDetectResult: "",
      select: false,
    })
  },

  button_upload: function(e){
    wx.showLoading({
      title: '上传中...',
    })
    this.setData({
      upload_enable: 'true',
    })
    uploadUserInfo(this);
  }

})

function uploadUserInfo(that) {

  if (that.data.picBase64 == null){
    return;
  }
  console.log('unitno： '+that.data.unitno)
  isTaking = true;
  //Constant.PICDETECT_URL
  wx.request({
    url: Constant.BASEURL + Constant.PICDETECT_URL,
    method: 'POST',
    data: { "personphoto": that.data.picBase64},
    success: function(res){
      
      var retCode = res.data.obj;
      console.log(retCode)
      if (retCode == "0"){
        if (that.data.isVisitor) {
          let pages = getCurrentPages();
          let prePage = pages[pages.length - 2];
          prePage.setData({
            photoPath: that.data.photo,
            imageSelect: true,
            picId: '',
          });
          wx.navigateBack({
            delta: 1,
          })
          return;
        }
        wx.request({
          url: Constant.BASEURL + Constant.UPLOAD_URL,
          method: 'POST',
          data: {
            "personname": that.data.userName, "personidcardno": that.data.cardNumber, "personphoneno": that.data.phoneNum, "persondoorno": that.data.hourseNum, "unitno": that.data.unitno, "persontype": that.data.typecode, "personphoto": that.data.picBase64
            , "openid": app.globalData.openid},
          success: function (res) {
            console.log(res.data)
            wx.hideLoading();
            if (res.data.ok) {
              // wx.navigateTo({ 
              //   url: '../confirm/confirm?personname=' + that.data.userName + "&personidcardno=" + that.data.cardNumber + "&personphoneno=" + that.data.phoneNum + "&persondoorno=" + that.data.hourseNum + "&unitno=" + that.data.unitno + "&persontype=" + that.data.typecode + "&sex=" + that.data.sex + "&cardType=" + that.data.cardType + "&wordType=" + that.data.wordType + "&role=" + that.data.role + "&location=" + that.data.location + "&community=" + that.data.community + "&buildNum=" + that.data.buildNum + "&photopath=" + that.data.photo + "&isUserInfo=" + false,
              // })


              wx.showModal({
                title: '提示',
                content: '注册成功',
                showCancel:false,
                success:function(res){
                  wx.reLaunch({
                    url: "../menu/menu"//这个是默认的单页
                  });   
                }
              })

            } else {
              wx.showToast({
                title: '注册失败',
                icon: 'none',
              })
            }
            that.setData({
              upload_enable: '',
            })
          },
          fail: function (res) {
            that.setData({
              faceDetectResult: "请检查网络连接",
              upload_enable: '',
            })
            wx.hideLoading()
          }
        })
      }else{
        let state_msg = "";
        if (retCode == Constant.STATE_ERROR_FILE_TYPE) {
          state_msg = '网络请求错误';
        } else if (retCode == Constant.STATE_ERROR_FILE_INCOMPLETE) {
          state_msg = '发送的数据不完整，请检查网络连接';
        } else if (retCode == Constant.STATE_ERROR_FILE_DATA) {
          state_msg = '不能解析图像数据';
        } else if (retCode == Constant.STATE_ERROR_FACE_NUM) {
          state_msg = '人脸数量不正确，请给一个正脸';
        } else if (retCode == Constant.STATE_ERROR_FACE_YIN_YANG) {
          state_msg = '光线不均匀，请到光线均匀的地方拍摄';
        } else if (retCode == Constant.STATE_ERROR_FACE_BORDER) {
          state_msg = '请将人脸放在画面中央';
        } else if (retCode == Constant.STATE_ERROR_FACE_RESOLUTION) {
          state_msg = '人脸太小，请靠近相机';
        } else if (retCode == Constant.STATE_ERROR_FACE_ANGLE) {
          state_msg = '人脸角度偏差太大，请给一个正脸';
        } else if (retCode == Constant.STATE_ERROR_IMAGE_QUALITY) {
          state_msg = '图像质量太差';
        } else {
          state_msg = '未知错误，错误码' + retCode;
        }
        wx.hideLoading()
        wx.showToast({
          title: state_msg,
          icon: 'none'
        })
        that.setData({
          faceDetectResult: state_msg,
          upload_enable: '',
        })
        var interval = setInterval(function () {
          isTaking = false;
          clearInterval(interval)
        }, 3000) //循环间隔 单位ms
      }
    },
    fail: function (res) {
      console.log(res)
      that.setData({
        faceDetectResult: "请检查网络连接",
        upload_enable: '',
      })
      wx.hideLoading()
    }
  })
  
}

function picToBase64(path, that) {
  let manager = wx.getFileSystemManager();
  manager.readFile({
    filePath: path,
    encoding: 'base64',
    success: function (res) {
      console.log("编码base64成功")
      that.setData({
        picBase64: res.data
      })
    },
    fail: function (res) {
      console.log(res)
    }
  })
}